/* DRW 15/07/05
I wrote this to try and demonstrate some very basic usage of Ricard's
blobslib for OpenCV, cvblobslib_OpenCV_v2.zip available at the 
OpenCV community site.

I have only be using C/C++ for two weeks, adn OpenCV for half that. 
The code is almost certainly ugly so if anyone wants to rewrite it
PLEASE do!

It was written, built and run in Visual Studio 2003 .NET following 
the compilation and project setup instructions in the HOWTO Ricard has 
included as part of the latest release.

*/


// Include files
#include <stdlib.h>
// OpenCV
#include <OpenCV/cv.h>
#include <OpenCV/cxcore.h>
#include <OpenCV/highgui.h>
// Blobs
#include <Blob.h>
#include <BlobResult.h>


int main(int argc, char *argv[])
{
	// GENERATE AN IMAGE WITH BLOBS
	// delcare an image
	IplImage *img = 0;
	// initalise img as 640x480, 8bit, 1channel (i.e. greyscale)
	img = cvCreateImage(cvSize(640 ,480 ),IPL_DEPTH_8U,1);
	// make the image back
	cvSet(img, cvScalar(0));

	// make some blobs
	cvCircle( img, cvPoint(200 , 200 ), 10, CV_RGB(255, 255, 255), CV_FILLED, 1, 0);
	cvCircle( img, cvPoint(20 , 400 ), 4, CV_RGB(255, 255, 255), CV_FILLED, 1, 0);
	cvCircle( img, cvPoint(550 , 50 ), 25, CV_RGB(255, 255, 255), CV_FILLED, 1, 0);

	// FIND AND MARK THE BLOBS
	// delcare a set of blob results
	CBlobResult blobs;
	// get the blobs from the image, with no mask, using a threshold of 100
	blobs = CBlobResult( img, NULL, 100, true );
	// mark the blobs on the image
	int i;
	// delare a single blob
	CBlob Blob;
	// some vars
	int iMaxx, iMinx, iMaxy, iMiny, iMeanx, iMeany;
	// for each blob
	for  (i=0; i<blobs.GetNumBlobs(); ++i)
	{
		// get the blob info
		Blob = blobs.GetBlob(i);
		// get max, and min co-ordinates
		iMaxx=Blob.MaxX();
		iMinx=Blob.MinX();
		iMaxy=Blob.MaxY();
		iMiny=Blob.MinY();
		// find the average of the blob (i.e. estimate its centre)
		iMeanx=(iMinx+iMaxx)/2;
		iMeany=(iMiny+iMaxy)/2;
		// mark centre
		cvLine( img, cvPoint(iMeanx, iMeany), cvPoint(iMeanx, iMeany), CV_RGB(50, 50 , 50), 4, 8, 0 );
		// mark box around blob
		cvRectangle( img, cvPoint(iMinx , iMiny ), cvPoint ( iMaxx, iMaxy ), CV_RGB(150, 150, 150), 1, 8, 0);
		// print the blob centres
		printf("\n%d, X: %d, Y: %d\n", i, iMeanx, iMeany);
	}// each blob

	// display the image
	cvNamedWindow("image",1);
	cvShowImage("image", img);
	// keep image 'til keypress
	cvWaitKey(0);
	// release the image
	cvReleaseImage(&img);

	return 0;
}